Skip to content

[6403893][ONNX][AutoCast] Fix false-success TRT parse for large ModelProto#1928

Merged
galagam merged 2 commits into
NVIDIA:mainfrom
galagam:dev-gagam-bug-6403893
Jul 16, 2026
Merged

[6403893][ONNX][AutoCast] Fix false-success TRT parse for large ModelProto#1928
galagam merged 2 commits into
NVIDIA:mainfrom
galagam:dev-gagam-bug-6403893

Conversation

@galagam

@galagam galagam commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

What does this PR do?

Type of change: ? Bugfix

get_custom_layers silently returned 0 layers/tensors for in-memory ModelProtos at/above the protobuf 2GiB limit. Route such models through a temporary external-data file and parse_from_file(), matching the string-path behavior. Verified on the 8.12GB VLA trunk (28 layers/5468 tensors) and a synthetic 2.2GB model. Adds a regression test forcing the file-backed path.

Usage

# Add a code snippet demonstrating how to use this

Testing

Before your PR is "Ready for review"

Make sure you read and follow Contributor guidelines and your commits are signed (git commit -s -S).

Make sure you read and follow the Security Best Practices (e.g. avoiding hardcoded trust_remote_code=True, torch.load(..., weights_only=False), pickle, etc.).

  • Is this change backward compatible?: ✅
  • If you copied code from any other sources or added a new PIP dependency, did you follow guidance in CONTRIBUTING.md: N/A
  • Did you write any new necessary tests?: ✅
  • Did you update Changelog?: ❌
  • Did you get Claude approval on this PR?: ✅

Additional Information

Summary by CodeRabbit

Summary

  • Bug Fixes

    • Improved ONNX-to-TensorRT custom layer extraction for very large/complex in-memory ONNX models by switching to a file-backed parsing workflow using temporary external-data. Includes a conservative fallback when size evaluation isn’t reliable, ensuring stable parsing behavior.
    • Ensured custom-layer and tensor metadata are consistent between in-memory parsing and file-path parsing.
  • Tests

    • Added a regression test verifying get_custom_layers returns matching custom-layer lists and tensor metadata for in-memory versus file-path parsing, including a forced file-backed scenario.

@galagam
galagam requested review from a team as code owners July 6, 2026 10:28
@galagam
galagam requested a review from cjluo-nv July 6, 2026 10:28
@galagam

galagam commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

/claude review

@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: ba1a5b24-42e0-463d-953c-8a4bdb87c812

📥 Commits

Reviewing files that changed from the base of the PR and between f764597 and 38f9c7d.

📒 Files selected for processing (2)
  • modelopt/onnx/trt_utils.py
  • tests/gpu/onnx/quantization/test_plugin.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • modelopt/onnx/trt_utils.py
  • tests/gpu/onnx/quantization/test_plugin.py

📝 Walkthrough

Walkthrough

Adds oversized-model detection for in-memory ONNX models, routes applicable models through temporary external-data files for TensorRT parsing, and tests parity across file-path, in-memory, and forced file-backed modes.

Changes

File-backed ONNX parsing support

Layer / File(s) Summary
ByteSize check and imports
modelopt/onnx/trt_utils.py
Adds copy import and _requires_file_backed_parse() to compare ModelProto.ByteSize() with onnx.checker.MAXIMUM_PROTOBUF, defaulting to file-backed parsing on failure.
Three-way parsing flow in get_custom_layers
modelopt/onnx/trt_utils.py
Uses parse_from_file for paths, temporary external-data serialization for applicable in-memory models, and direct serialized parsing otherwise.
Regression test for parity
tests/gpu/onnx/quantization/test_plugin.py
Compares custom-layer and tensor metadata across file-path, in-memory, and forced file-backed parsing.

Estimated code review effort: 2 (Simple) | ~15 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant get_custom_layers
  participant _requires_file_backed_parse
  participant TempFileSave
  participant TrtParser

  Caller->>get_custom_layers: onnx_path (str or ModelProto)
  alt onnx_path is string
    get_custom_layers->>TrtParser: parse_from_file(onnx_path)
  else onnx_path is ModelProto
    get_custom_layers->>_requires_file_backed_parse: check ByteSize()
    alt requires file-backed parse
      _requires_file_backed_parse-->>get_custom_layers: True
      get_custom_layers->>TempFileSave: deepcopy + save external data
      get_custom_layers->>TrtParser: parse_from_file(temp_path)
    else
      _requires_file_backed_parse-->>get_custom_layers: False
      get_custom_layers->>TrtParser: parse(SerializeToString())
    end
  end
  TrtParser-->>get_custom_layers: parsed layers or errors
Loading

Suggested reviewers: cjluo-nv, ajrasane

🚥 Pre-merge checks | ✅ 6
✅ Passed checks (6 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the main fix: addressing a false-success TensorRT parse for large ModelProto objects at/above the 2GB protobuf limit.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Security Anti-Patterns ✅ Passed No new hardcoded unsafe loads, trust_remote_code=True, exec/eval, nosec additions, or new deps in non-test modelopt/examples diffs.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

with tempfile.TemporaryDirectory(prefix="modelopt_trt_") as tmpdir:
model_path = os.path.join(tmpdir, "model.onnx")
# Deep-copy so externalization doesn't strip weights from the caller's model.
model_copy = copy.deepcopy(onnx_path)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SUGGESTION] copy.deepcopy(onnx_path) transiently doubles peak RAM for exactly the models this path targets — an 8GB ModelProto needs ~16GB before onnx.save streams weights to disk. The deep-copy is necessary for correctness (onnx.save(save_as_external_data=True) mutates the proto in place, stripping raw_data from the caller's model), so this isn't a bug — but on the 8GB VLA trunk case cited in the PR description it may be tight on constrained hosts.

If it ever bites, an alternative that avoids the copy is to externalize in place and restore afterward (e.g. onnx.save(onnx_path, ...) then onnx.load_external_data_for_model(onnx_path, tmpdir) to re-hydrate the caller's proto), or wrap in try/finally to guarantee re-hydration on parse failure. Non-blocking; the current approach is the safest correctness-wise.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The peak memory usage is at ReferenceRunner where we define an auxiliary graph with every intermediate tensor being a graph output. The 2x memory usage here is not a bottleneck.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree!

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude review passed — no blocking issues found. LGTM

Scope: Reviewed the 2 files in this PR's authoritative changed-file list (modelopt/onnx/trt_utils.py, tests/gpu/onnx/quantization/test_plugin.py). The two-dot git diff origin/main HEAD surfaced many unrelated files due to the shallow-checkout divergence between the local origin/main tip and the true merge base — those are not part of this PR and were excluded.

Findings: CRITICAL: 0, IMPORTANT: 0, SUGGESTION: 1

Assessment — low risk. Focused, well-targeted bugfix. get_custom_layers previously silently returned an empty network (0 layers/0 tensors) for in-memory ModelProtos at/above the protobuf 2 GiB limit because TensorRT's parser.parse(bytes) fails quietly while SerializeToString() succeeds. The fix routes over-limit (or un-sizeable) in-memory models through a temporary external-data file + parse_from_file(), matching the existing string-path branch and ModelOpt's file-backed policy elsewhere in this module.

Verified:

  • onnx.checker.MAXIMUM_PROTOBUF is a valid constant, already used with the same >= MAXIMUM_PROTOBUF idiom at trt_utils.py:382.
  • The ByteSize()-overflow except branch conservatively routes to the file path, consistent with load_onnx_model's handling.
  • copy.deepcopy correctly shields the caller's model from in-place externalization by onnx.save; both in-memory callers pass a model the caller still owns.
  • The regression test forces the file-backed path via monkeypatch and cross-checks results against both the in-memory fast path and the string-path baseline. Backward compatible — the small-model fast path is unchanged.

The single SUGGESTION concerns transient peak-RAM doubling from the deep-copy on multi-GB models — non-blocking, and the current approach is the correctness-safe choice.

@galagam galagam self-assigned this Jul 6, 2026
@galagam
galagam requested review from ajrasane and gcunhase July 6, 2026 10:37
@codecov

codecov Bot commented Jul 6, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 57.89474% with 8 lines in your changes missing coverage. Please review.
✅ Project coverage is 77.25%. Comparing base (21d0069) to head (38f9c7d).

Files with missing lines Patch % Lines
modelopt/onnx/trt_utils.py 57.89% 8 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1928      +/-   ##
==========================================
+ Coverage   76.50%   77.25%   +0.74%     
==========================================
  Files         525      525              
  Lines       59257    59273      +16     
==========================================
+ Hits        45337    45790     +453     
+ Misses      13920    13483     -437     
Flag Coverage Δ
examples 42.70% <52.63%> (-0.73%) ⬇️
gpu 58.13% <36.84%> (-0.05%) ⬇️
unit 54.96% <21.05%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@gcunhase gcunhase left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you think the comment from Claude review should be a concern?

The single SUGGESTION concerns transient peak-RAM doubling from the deep-copy on multi-GB models.

Otherwise, LGTM!

@galagam

galagam commented Jul 6, 2026

Copy link
Copy Markdown
Contributor Author

Do you think the comment from Claude review should be a concern?

The single SUGGESTION concerns transient peak-RAM doubling from the deep-copy on multi-GB models.

Otherwise, LGTM!

@gcunhase Thanks for holding me accountable... Replied in the original thread.
#1928 (comment)

@galagam
galagam force-pushed the dev-gagam-bug-6403893 branch from b52dc3f to c8a5a30 Compare July 7, 2026 11:15
@copy-pr-bot

copy-pr-bot Bot commented Jul 7, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning

CodeRabbit couldn't request changes on this pull request because it doesn't have sufficient GitHub permissions.

Please grant CodeRabbit Pull requests: Read and write permission and re-run the review.

👉 Steps to fix this

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/gpu/onnx/quantization/test_plugin.py`:
- Line 163: Move the `modelopt.onnx.trt_utils as trt_utils` import out of the
test body and into the module-level imports in `test_plugin.py`. This import is
only used to support `monkeypatch.setattr`, so it should be declared alongside
the other top-level `modelopt.onnx.trt_utils` imports rather than inside the
test. Remove the in-function import and keep the `trt_utils` reference available
for the existing monkeypatch usage.
🪄 Autofix (Beta)

❌ Autofix failed (check again to retry)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: e2d67f9b-19fd-4e4f-a16a-79d54c790fd8

📥 Commits

Reviewing files that changed from the base of the PR and between d290839 and c8a5a30.

📒 Files selected for processing (2)
  • modelopt/onnx/trt_utils.py
  • tests/gpu/onnx/quantization/test_plugin.py

Comment thread tests/gpu/onnx/quantization/test_plugin.py Outdated
@coderabbitai

coderabbitai Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Note

Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.

An unexpected error occurred while generating fixes: Not Found - https://docs.github.com/rest/git/refs#get-a-reference

@galagam
galagam force-pushed the dev-gagam-bug-6403893 branch from d5228a7 to 55b0296 Compare July 8, 2026 14:13
@galagam
galagam force-pushed the dev-gagam-bug-6403893 branch from 55b0296 to f764597 Compare July 15, 2026 14:39
galagam added 2 commits July 16, 2026 11:45
…Proto

get_custom_layers silently returned 0 layers/tensors for in-memory
ModelProtos at/above the protobuf 2GiB limit. Route such models through a
temporary external-data file and parse_from_file(), matching the string-path
behavior. Verified on the 8.12GB VLA trunk (28 layers/5468 tensors) and a
synthetic 2.2GB model. Adds a regression test forcing the file-backed path.

Signed-off-by: Gal Hubara Agam <96368689+galagam@users.noreply.github.com>
Signed-off-by: Gal Hubara-Agam <96368689+galagam@users.noreply.github.com>
Signed-off-by: Gal Hubara Agam <96368689+galagam@users.noreply.github.com>
@galagam
galagam force-pushed the dev-gagam-bug-6403893 branch from f764597 to 38f9c7d Compare July 16, 2026 18:46
@galagam
galagam merged commit bd1864d into NVIDIA:main Jul 16, 2026
53 of 54 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants